import { Base64 } from "js-base64";

const key = "metaData";

/**
 * 在sessionStorage中存储
 * @param {*} data 
 */
const setStorage = (data) => {
    if (data) {
        sessionStorage.setItem(key, Base64.encode(JSON.stringify(data)));
    }
    
}

/**
 * 在sessionStorage中获取
 */
const getStorage = () => {
    const data = sessionStorage.getItem(key);
    if (data) {
        return JSON.parse(Base64.decode(data));
    } else {
        return {};
    }
}

/**
 * 在sessionStorage中存储特定值
 * @param {*} key 键
 * @param {*} value 值
 */
const addToStorage = (key, value) => {
    const data = getStorage();
    data[key] = value;
    setStorage(data);
}

/**
 * 在sessionStorage中存储特定值
 * @param {*} value 对象
 */
 const mergeToStorage = (value) => {
    const data = getStorage();
    setStorage({...data, ...value});
}

/**
 * 清空存储
 */
const clearStorage = () => {
    sessionStorage.removeItem(key);
}

const getItem = (key) => {
    const data = getStorage();
    return data[key];
}

const storageUtil = {
    set: setStorage,
    get: getStorage,
    add: addToStorage,
    merge: mergeToStorage,
    getItem: getItem,
    clear: clearStorage,
}

export default storageUtil;